<!--
Copyright 2022 Huawei Cloud Computing Technology Co., Ltd.

> Licensed under the Apache License, Version 2.0 (the "License");
> you may not use this file except in compliance with the License.
> You may obtain a copy of the License at

>     http://www.apache.org/licenses/LICENSE-2.0

> Unless required by applicable law or agreed to in writing, software
> distributed under the License is distributed on an "AS IS" BASIS,
> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
> See the License for the specific language governing permissions and
> limitations under the License.
-->

<!DOCTYPE html>
<html>
  <head>
    <title>h5 demo</title>
    <meta charset="utf-8" />
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" />
    <style>
      html,
      body {
        margin: 0;
        padding: 0;
      }
      .container {
        width: 100%;
        height: 100%;
        background: black;
      }
      .loading {
        width: 50px;
        height: 50px;
        position: absolute;
        top: calc(50% - 25px);
        left: calc(50% - 25px);
        -ms-animation: load-anim 2s linear infinite;
        -webkit-animation: load-anim 2s linear infinite;
        -moz-animation: load-anim 2s linear infinite;
        -webkit-animation: load-anim 2s linear infinite;
        -o-animation: load-anim 2s linear infinite;
        animation: load-anim 2s linear infinite;
      }
      @keyframes load-anim {
        from {
          -ms-transform: rotate(0deg);
          -moz-transform: rotate(0deg);
          -webkit-transform: rotate(0deg);
          -o-transform: rotate(0deg);
          transform: rotate(0deg);
        }
        to {
          -ms-transform: rotate(360deg);
          -moz-transform: rotate(360deg);
          -webkit-transform: rotate(360deg);
          -o-transform: rotate(360deg);
          transform: rotate(360deg);
        }
      }
      #network-info {
        pointer-events: none;
        position: absolute;
        top: 0px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        width: 100%;
        color: #3AC295;
      }
      #keyboard-dialog {
        border: 1px solid lightblue;
        border-radius: 10px;
      }
      .play-ctr-btn {
        display: inline-block;
        background: #fff;
        border: 1px solid #595959;
        text-align: center;
        height: 30px;
        line-height: 30px;
        border-radius: 5px;
        font-size: 14px;
      }
      .message-modal, .exit-modal {
        display: none;
        width: 300px;
        height: 200px;
        position: absolute;
        z-index: 999;
        top: 50%;
        left: 50%;
        background-color: #fff;
        border: 1px solid #dfe1e6;
        border-radius: 5px;
        transform: translate(-50%, -50%);
      }
      .header-content {
        height: 20%;
        line-height: 20%;
        text-align: center;
        font-size: 16px;
      }
      .body-content {
        text-align: center;
        height: 40%;
      }
      .footer-content {
        height: 20%;
        border-top: 1px solid #dfe1e6;
      }
      .button-alone {
        width: 100%;
        height: 100%;
        border: none;
        text-align: center;
        background-color: #fff;
      }
      .control-btn {
        display: none;
        user-select: none;
        font-size: 14px;
        line-height: 40px;
        text-align: center;
        width: 40px;
        height: 40px;
        position: fixed;
        z-index: 999;
        top: 15%;
        left: 35%;
        background-color: #fff;
        border: 1px solid #dfe1e6;
        border-radius: 50%;
      }
      .button-modal{
        display: none;
        width: 255px;
        height: 200px;
        position: absolute;
        z-index: 999;
        top: 50%;
        left: 50%;
        background-color: rgba(0, 0, 0, 0.4);
        border-radius: 5px;
        transform: translate(-50%, -50%);
      }
      .button-network,.button-exit, .fullscreen-btn{
        width: 100%;
        height: 38px;
        margin-bottom: 10px;
      }
      .radio-group {
        color: #ffffff;
        display: flex;
        justify-content: space-around;
        align-items: center;
        height: 55px;
      }
      input[type="radio"] {
        transform: scale(1.5);
      }
      .exit-btn {
        float: left;
        width: 50%;
        height: 100%;
        border: none;
        text-align: center;
        background-color: #fff;
      }
      .cancel-btn {
        float: right;
        width: 50%;
        height: 100%;
        border: none;
        text-align: center;
        background-color: #fff;
      }
    </style>
  </head>

  <body onunload="cloudapp.exit()">
    <div id="fullscreen-container"
      class="fullscreen-container">
      <div id="container"
          class="broadway container"
          workers="false"
          render="true"
          webgl="auto">
        <div class="loading"
            id="loading">
          <svg xmlns="http://www.w3.org/2000/svg"
              width="50"
              height="50">
            <path fill="#909090"
                  d="M22.5 2h5v11h-5z" />
            <path fill="#B0B0B0"
                  d="M6.97 10.504l3.535-3.535 7.778 7.778-3.536 3.535z" />
            <path fill="silver"
                  d="M2 22.5h11v5H2z" />
            <path fill="#D0D0D0"
                  d="M10.504 43.03l-3.535-3.535 7.779-7.777 3.535 3.536z" />
            <path fill="#303030"
                  d="M22.5 37h5v11h-5z" />
            <path fill="#505050"
                  d="M43.03 39.497l-3.535 3.533-7.776-7.78 3.536-3.534z" />
            <path fill="#707070"
                  d="M37 22.5h11v5H37z" />
            <path fill="#909090"
                  d="M39.496 6.969l3.535 3.536-7.78 7.777-3.534-3.536z" />
          </svg>
        </div>
        <div id="network-info">
          网络时延 <span id="network-delay"></span>ms 码率 <span id="network-bit-rate"></span>kbps
        </div>
        <div class="message-modal" id="messageModal">
          <div class="header-content">
            <p>温馨提示</p>
          </div>
          <div class="body-content">
            <p class="msg" id="msgContent"></p>
          </div>
          <div class="footer-content">
            <button class="button-alone" onclick="closeModal()">退出</button>
          </div>
        </div>
        <div class="exit-modal" id="exitModal">
          <div class="header-content">
            <p>温馨提示</p>
          </div>
          <div class="body-content">
            <p class="msg" id="msgContent">确定退出吗？</p>
          </div>
          <div class="footer-content">
            <button class="exit-btn" onclick="exitPhone()">退出</button>
            <button class="cancel-btn" onclick="closeExitModal()">取消</button>
          </div>
        </div>
        <div id="controlBtn" class="control-btn">CTRL</div>
        <div id="buttonModal" class="button-modal">
          <div class="radio-group">
            <div class="UHD">
              <input type="radio" name="clarity" id="UHD" value="UHD" onchange="radioChange(event)">
              <label for="UHD">超清</label>
            </div>
            <div class="HD">
              <input type="radio" name="clarity" id="HD" value="HD" checked onchange="radioChange(event)">
              <label for="HD">高清</label>
            </div>
            <div class="SD">
              <input type="radio" name="clarity" id="SD" value="SD" onchange="radioChange(event)">
              <label for="SD">流畅</label>
            </div>
          </div>
          <button class="button-network" id="netWorkBtn" onclick="toggleNetworkInfo(event)">关闭时延数据</button>
          <button class="fullscreen-btn" id="toggleFullscreen">全屏</button>
          <button class="button-exit" id="exitBtn" onclick="showExitModal()">退出云手机</button>
        </div>
      </div>
    </div>
    <div style="margin: 20px auto 10px;display: none;">
      <button type="button"
              class="play-ctr-btn"
              onclick="cloudapp.pause()">Pasue</button>
      <button type="button"
              class="play-ctr-btn"
              onclick="cloudapp.resume()">Resume</button>
      <button type="button"
              class="play-ctr-btn"
              onclick="exit()">Exit</button>
      <button type="button"
              id="fullscreen"
              class="play-ctr-btn"
              onclick="fullscreenToggle('fullscreen-container')">Fullscreen</button>
      <button type="button"
              id="network"
              class="play-ctr-btn"
              onclick="toggleNetworkInfo()">Network</button>
      <select id="resolution"
              class="play-ctr-btn"
              onchange="setResolution()">
        <option value="DISPLAY_480P">480P</option>
        <option value="DISPLAY_540P">540P</option>
        <option value="DISPLAY_720P"
                selected="selected">720P</option>
        <option value="DISPLAY_1080P">1080P</option>
      </select>
      <a id="trustHost"
        target="_blank"
        class="play-ctr-btn"
        href="">信任目标机器</a>
    </div>
    <!-- <script type="text/javascript" src="lib/vconsole.min.js"></script> -->
    <script type="text/javascript"
            src="<%= htmlWebpackPlugin.files.chunks.CloudApp.entry %>"></script>
    <script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
    <script type="text/javascript">
      // VConsole 默认会挂载到 `window.VConsole` 上
      var vConsole = new window.VConsole();
      // 从url中获取ip和port
      var urlParams = new URLSearchParams(window.location.search);
      var urlIp = urlParams.get('ip');
      var urlPort = urlParams.get('port');
      if (urlIp && urlPort) {
        let hostStr = urlIp + ':' + urlPort;
        sessionStorage.setItem('cloudPhoneHost', hostStr);
      }
      const appId = sessionStorage.getItem('appId');
      const appKey = sessionStorage.getItem('appKey');
      const env = sessionStorage.getItem('env');
      const roomId = sessionStorage.getItem('roomId');
      const channelType = sessionStorage.getItem('channelType');
      var cloudPhoneHost = sessionStorage.getItem('cloudPhoneHost');
      if (cloudPhoneHost) {
        var hostParams = cloudPhoneHost.split(':');
        var cloudIp = hostParams[0];
        var cloudPort = hostParams[1];
      } else {
        let localHref = window.location.href;
        if (localHref.indexOf('demo.html') > -1) {
          localHref = window.location.href.replace('demo.html', 'enter.html');
        } else {
          localHref = window.location.href.replace('index', '');
        }
        
        window.location.href = localHref;
      }

      var parseSearch = function () {
        var search = location.search.substr(1);
        var kvs = search.split("&");
        var params = {};
        kvs.forEach(item => {
          var [key, value] = item.split("=");
          key && (params[key] = value);
        });
        return params;
      }
      var params = parseSearch();
      var hosts = {
        anb139_32: {
          ip: cloudIp,
          port: cloudPort,
        },
      }
      var config = Object.assign({}, hosts.anb139_32, params);
      var getConfig = {
        get basePath() {
          let path = window.location.origin;
          let pathname = window.location.pathname;
          let demoIdx = pathname.lastIndexOf('/demo');
          let indexIdx = pathname.lastIndexOf('/index');
          if (demoIdx !== -1) {
            return path + pathname.substr(0, demoIdx);
          } else if (indexIdx !== -1) {
            return path + pathname.substr(0, indexIdx);
          } else {
            return path;
          }
        },
        get libPath() {
          return this.basePath + '/lib/'
        }
      };
      var commonLibPath = getConfig.libPath;
      var params = {
        ip: config.ip,
        port: config.port,
        appId: appId,
        appKey: appKey,
        env: env,
        roomId: roomId,
        channelType: channelType,
        connect_uri: 'wss://' + [config.ip, config.port].join(':'),
        session_id: '32uuid'.padStart(32, '0'),
        background_timeout: '60',
        available_playtime: '6000',
        ticket: '256random'.padStart(256, '0'),
        aes_key: '11111111111111111111111111111111',
        auth_ts: 'test_auth_ts',//String(Date.now()),
        _debug: true,
        // _mock: true,
        touch_timeout: 600,
        auto_rotate: true,
        libPath: commonLibPath, // 配置库文件地址
        decoder_type: 'H264', // H265\H264
        microPhoneOutputType: 'OPUS' // PCM或OPUS
      };
      try {
        if (CloudApp.isSupport()) {
          var cloudapp = new CloudApp("container", params);
          cloudapp.on("appStateChange", function (event, data) {
            console.log(event, data);
            var state = data && data.state;
            var STATE_CONFIG = {
              STARTED: 2048,
              RESUMED: 5120,
              MEDIA_CONFIG_SUCCESS: 8448
            };

            var normalStates = [STATE_CONFIG.STARTED, STATE_CONFIG.RESUMED, STATE_CONFIG.MEDIA_CONFIG_SUCCESS];
            document.getElementById("loading").style.display = normalStates.includes(state) ? 'none' : 'block';
            showAlertModal(data);
            startsuccessCallBack(data);
          });

          cloudapp.on("netStateChange", function (event, data) {
            var delayElement = document.getElementById('network-delay');
            var bitrateElement = document.getElementById('network-bit-rate');
            delayElement.innerHTML = data.delay;
            bitrateElement.innerHTML = data.bitrate;
          });

          // 音量设置，范围为 0 ~ 100
          cloudapp.setVolume(60);

          cloudapp.on("audioStateChange", function (event, data) {
            console.log(event, data);
          });

          cloudapp.on("cloudAppData", function (event, data) {
            var typedArray = new Uint8Array(data);
            var str = decodeUTF8(typedArray);
            console.log(event, str)
          });

          window.cloudapp = cloudapp;
          window.sendDataToCloudApp = function (str) {
            var utf8Array = encodeUTF8(str);
            var typedArray = new Uint8Array(utf8Array);
            window.cloudapp.sendDataToCloudApp(typedArray.buffer);
          };
          document.getElementById("trustHost").href = 'https://' + [config.ip, config.port].join(':');
        }
      } catch (e) {
        console.log(e);
      }

      function toggleNetworkInfo(event) {
        var networkInfoElement = document.getElementById('network-info');
        networkInfoElement.hidden = !networkInfoElement.hidden;
        if (networkInfoElement.hidden) {
          event.target.innerHTML = '显示时延数据';
        } else {
          event.target.innerHTML = '关闭时延数据';
        }
      }

      function showExitModal() {
        const buttonModalEle = document.getElementById('buttonModal');
        const exitModalEle = document.getElementById('exitModal');
        buttonModalEle.style.display = 'none';
        exitModal.style.display = 'block';
      }

      function exitPhone() {
        exit();
        closeExitModal();
      }

      function closeExitModal() {
        const exitModalEle = document.getElementById('exitModal');
        exitModal.style.display = 'none';
      }

      function exit() {
        cloudapp.exit();
        var networkInfoElement = document.getElementById('network-info');
        networkInfoElement.hidden = true;

        let isAppUse = false;
        try {
          CasCallback.exit();
          isAppUse = true;
        } catch (error) {
          isAppUse = false;
        }
        
        if (!isAppUse) {
          sessionStorage.removeItem('cloudPhoneHost');
          const currentUrl = window.location.href;
          if (currentUrl.indexOf('index.html') > -1) {
            window.location.href = currentUrl.replace('index.html', 'enter.html');
          } else {
            window.location.href = currentUrl.replace('index', '');
          }
        }
      }

      function fullscreenToggle(fullscreenEle) {
        cloudapp.fullscreenToggle(fullscreenEle);
        console.log("Is in fullscreen?", cloudapp.isFullscreen());
      }

      function setResolution() {
        var dom = document.getElementById('resolution');
        if (!dom) {
          return;
        }
        var resolution = dom.options[dom.selectedIndex || 0].value;
        cloudapp.setResolution(CloudApp.RESOLUTIONS[resolution]);
      }

      function encodeUTF8(textStr) {
        var encodedStr = encodeURIComponent(textStr);
        var encodedArray = [];
        for (var i = 0; i < encodedStr.length; i++) {
          var cur = encodedStr.charAt(i);
          if (cur === '%') {
            var code = encodedStr.charAt(i + 1) + encodedStr.charAt(i + 2);
            encodedArray.push(parseInt(code, 16));
            i += 2;
          } else {
            encodedArray.push(cur.charCodeAt(0));
          }
        }

        return encodedArray;
      }

      function decodeUTF8(utf8Array, start, end) {
        var len = utf8Array.length;
        start = start || 0;
        end = end || len;
        if (start < 0 || start >= len || end < 0 || end > len) {
          return '';
        }

        var encodedStr = '';
        for (var i = start; i < end; i++) {
          encodedStr += '%' + utf8Array[i].toString(16);
        }

        return decodeURIComponent(encodedStr);
      }

      function showAlertModal(data) {
        const modalEle = document.getElementById('messageModal');
        const msgEle = document.getElementById('msgContent');
        const startSuccessState = 512;
        // 连接成功需要关闭已显示的弹框
        if (data.state === startSuccessState) {
          if(modalEle.style.display === 'block') {
            modalEle.style.display = 'none';
            return;
          }
        }
        if (data.tip) {
          msgEle.innerHTML = data.tip;
          modalEle.style.display = 'block';
        }
      }

      function closeModal() {
        const modalEle = document.getElementById('messageModal');
        modalEle.style.display = 'none';
        exit();
      }

      function startsuccessCallBack(data){
        const connectSuccessState = 2048;
        if (data.state === connectSuccessState) {
          closeCtrlModal();
          try {
            CasCallback.startSuccessCallback();
          } catch (error) {}
        }
      }

      function radioChange(event) {
        const checkedVal = event && event.target.value;
        cloudapp.setResolution(checkedVal);
      }

      function closeCtrlModal() {
        const ctrlEle = document.getElementById('controlBtn');
        const buttonModalEle = document.getElementById('buttonModal');
        const playContainer = document.querySelector('article');
        const playerElement = playContainer.shadowRoot.querySelector('#playCanvas') || playContainer.shadowRoot.querySelector('#phoenixVideo');
        const fullscreenBtn = document.getElementById('toggleFullscreen');
        ctrlEle.style.display = 'block';

        ctrlEle.addEventListener('click', (event) => {
          if(buttonModalEle.style.display !== 'block') {
            buttonModalEle.style.display = 'block';
          } else {
            buttonModalEle.style.display = 'none';
          }
        });

        if (/(iPhone|iPad|iPod|iOS|Android)/i.test(navigator.userAgent)) {
          fullscreenBtn.style.display = 'block';
          playerElement.addEventListener('touchend', (event) => {
            if(!buttonModalEle.contains(event.target) && !ctrlEle.contains(event.target)) {
              buttonModalEle.style.display = 'none';
            }
          });
        } else {
          fullscreenBtn.style.display = 'none';
          document.addEventListener('click', (event) => {
            if(!buttonModalEle.contains(event.target) && !ctrlEle.contains(event.target)) {
              buttonModalEle.style.display = 'none';
            }
          });
        }

        buttonModalEle.addEventListener('click', (event) => {
          event.stopPropagation();
        });
      }
    </script>
  </body>

</html>
